/*数据互联*/
import React from "react";
import { Input } from "antd";
import set from "lodash/set";
import { useFormField } from "../../context/form-context";
import { useForm } from "../../context/metadata-context";
import DataConnect from "./DataConnect";/*数据互联组件*/
import { useInject } from "../../context/inject-context";
import { reloadField } from "../../context/metadata-context";//表单字段reload事件
import eventBus, { useSubscribe } from "../../eventBus";
import { parseToArray } from "../../utils";

/**
 * @param {string} url - 需要替换的url
 * @param {object} itemData - 当前组件的值
 * @param {string} host - tplData.ServerAddr
 * @param {Array} column - 当前字段的列属性
 * 
 * @returns 
 */
function replaceHref({
  url,
  itemData,
  host,
  column
}){
  url = url.toLowerCase();
  var isExist = url.indexOf("?");
  var dic = {};
  for(var key in itemData){
      if(existColSetting({fdcode: key, column: column})){
          dic["["+key.toLowerCase()+"]"] = itemData[key];
      }
  }
  var regex = /\[(.+?)\]/g;
  var arr = url.match(regex);
  arr && arr.forEach(function(rplc_key){
      var rplc_value = dic[rplc_key] || "";
      if(isExist < 0){
          url = url.replace(rplc_key, htmlUnescape(rplc_value));
      }else {
          url = url.replace(rplc_key, rplc_value);
      }
  });

  if(!url.startsWith("http://") && !url.startsWith("https://") && host !== ""){
      if(url.indexOf("/") !== 0){
          url = "/"+url;
      }
      url = host + url;
  }
  return url;
};

function htmlUnescape(text){
  text = unescape(text);
  var replacer = {
      "&lt;":"<","&gt;":">","&amp;":"&","&quot;":"\""
  };
  for(var key in replacer){
      while(text.indexOf(key) > -1){                    
          text = text.replace(key,replacer[key]);
      }
  }
  return text;
};

function existColSetting({fdcode, column}){
  var exist = false;            
  column && column.forEach(function(col){
      if(col.code.toLowerCase() === fdcode.toLowerCase()) exist = true;
  });
  return exist;
};  

export {
  replaceHref
}